package com.allianz.webapps.secondController;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.allianz.frame.utils.Pdf2TifUtil;
import com.allianz.frame.utils.PropertiesUtil;
import com.allianz.frame.utils.StringUtil;
import com.allianz.webapps.common.CustomerContextHolder;
import com.allianz.webapps.dbpojo.AdT2NoticeRecordsKey;
import com.allianz.webapps.dbpojo.Note;
import com.allianz.webapps.dbpojo.QC;
import com.allianz.webapps.https.interfaces.bjca.BJCApojo;
import com.allianz.webapps.https.interfaces.bjca.PdfMessage;
import com.allianz.webapps.https.interfaces.util.HttpsUtil;
import com.allianz.webapps.service.AdT2NoticeRecordsService;
import com.allianz.webapps.service.NoteService;
import com.allianz.webapps.service.impl.CaPdfService;
import com.allianz.webapps.service.impl.HtmlParseService;
import com.allianz.webapps.service.impl.ImageUploadService;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@Controller
@RequestMapping(value = "/note")
public class NoteController {
	@Autowired
	private AdT2NoticeRecordsService adT2NoticeRecordsService;

	@Autowired
	private NoteService noteService;

	@Autowired
	private ObjectMapper objectMapper;

	private Logger logger = LoggerFactory.getLogger(getClass());
	// REALPATH = /app/azclportal_resource/resources/newtouch/
	private static String REALPARH = PropertiesUtil.getResourcePath();

	/*
	 * 界面请求
	 */
	@RequestMapping(value = "noteContent")
	public String noteCongtent(HttpServletRequest request,
			HttpServletResponse response) {
		return "views/page/noteDeal/noteContent";
	}

	@RequestMapping(value = "noteIssue")
	public String noteIssue(HttpServletRequest request,
			HttpServletResponse response) {
		return "views/page/noteDeal/noteIssue";
	}

	@RequestMapping(value = "quotationSign")
	public String noteReply(HttpServletRequest request,
			HttpServletResponse response) {
		return "views/page/noteDeal/quotationSign";
	}

	@RequestMapping(value = "affirmNoteReply")
	public String noteSign(HttpServletRequest request,
			HttpServletResponse response) {
		return "views/page/noteDeal/affirmNoteReply";
	}


	@RequestMapping("/uploadOne")
	@ResponseBody
	public void uploadOne(@RequestParam(value = "jsonParam") String jsonParam,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JSONObject obj = JSONObject.fromObject(jsonParam);
		String imageData = (String) obj.get("image");
		String type = (String) obj.get("idType");
		String policyRef = (String) obj.get("policyRef");
		String contractId = (String) obj.get("contractId");

		Assert.hasLength(imageData, "未获得所拍照片");
		Assert.hasLength(type, "未获得所拍照片类型");
		Assert.hasLength(policyRef, "未获得保单号");
		Assert.hasLength(contractId, "未获得contractId");
		// 实际地址
		File f = new File(REALPARH + "private/NOTE/" + policyRef + "/"
				+ contractId + "/" + "signed/");
		if (f.exists()) {
			if (f.isFile()) {
				f.delete();
			}
		} else {
			f.mkdirs();
		}
		String path = REALPARH + "private/NOTE/" + policyRef + "/" + contractId
				+ "/" + "signed/" + type + "_"
				+ ImageUploadService.returnType(type) + ".jpg";
		boolean bn = ImageUploadService.uploadUtil(imageData, path);
	}
	// 获取所有照片
	@RequestMapping("/getPic")
	@ResponseBody
	public Map<String, List<File>> getPic(
			@RequestParam(value = "jsonParam") String jsonParam,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JSONObject obj = JSONObject.fromObject(jsonParam);
		List<String> typeList = (List<String>) obj.get("typeList");
		String policyRef = (String) obj.get("policyRef");
		String contractId = (String) obj.get("contractId");
		Assert.notEmpty(typeList, "图片类型不能为空");
		Assert.hasLength(policyRef, "保单号不能为空");
		Assert.hasLength(contractId, "contractId不能为空");
		Map<String, List<File>> map = new HashMap<String, List<File>>();

		String folderPath = REALPARH + "private/NOTE/" + policyRef + "/"
				+ contractId + "/" + "signed/";
		map = ImageUploadService.getPicPhotoMap(policyRef, policyRef, typeList,
				folderPath,"NOTE");
		return map;
	}

	// 删除照片
	@RequestMapping("/deletePic")
	@ResponseBody
	public Map<String, String> deletePic(
			@RequestParam(value = "jsonParam") String jsonParam,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 获得数据 校验数据
		JSONObject obj = JSONObject.fromObject(jsonParam);
		String type = (String) obj.get("id");
		String policyRef = (String) obj.get("policyRef");
		String contractId = (String) obj.get("contractId");
		Assert.hasLength(type, "图片类型不能为空");
		Assert.hasLength(policyRef, "保单号不能为空");
		Assert.hasLength(contractId, "contractId不能为空");
		// 得到地址
		Map<String, String> map = new HashMap<String, String>();
		List<String> pathList = new ArrayList<String>();
		String path = REALPARH + "private/NOTE/" + policyRef + "/" + contractId
				+ "/" + "signed/" + type + "_"
				+ ImageUploadService.returnType(type) + ".jpg";
		pathList.add(path);
		// 删除数据 返回结果
		boolean bn = ImageUploadService.deletePic(pathList);
		if (bn) {
			map.put("result", "Y");
		}

		return map;
	}

	/**
	 * 显示图片
	 * 
	 * @throws IOException
	 */
	@RequestMapping(value = "/showPic")
	public void showUserImg(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String type = request.getParameter("type");
		String policyRef = request.getParameter("policyRef");
		String contractId = request.getParameter("contractId");
		String folderPath = REALPARH + "private/NOTE/" + policyRef + "/"
				+ contractId + "/" + "signed/" + type + "_"
				+ ImageUploadService.returnType(type) + ".jpg";
		File f = new File(folderPath);
		int length = 0;
		ServletOutputStream op;
		try {
			op = response.getOutputStream();
		} catch (IOException e) {
			throw new IOException("io流错误");
		}
		response.setContentLength((int) f.length());
		response.setContentType("image/jpeg");
		response.setHeader("Content-Disposition", "inline; filename=" + type);
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "No-cache");
		response.setHeader("Cache-Control", "no-store");
		response.setDateHeader("Expires", 0);

		byte[] bytes = new byte[1024];
		DataInputStream in;
		try {
			in = new DataInputStream(new FileInputStream(f));
			while ((in != null) && ((length = in.read(bytes)) != -1)) {
				op.write(bytes, 0, length);
			}
			op.close();
			in.close();
			response.flushBuffer();
		} catch (FileNotFoundException e) {
			throw new Exception("文件未找到");
		} catch (IOException e) {
			throw new IOException("io流错误");
		}

	}

	/**
	 * 显示pdf合成图片
	 * 
	 * @throws IOException
	 */
	@RequestMapping(value = "/showPdfPic")
	public void showPdfImg(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String contractId = request.getParameter("contractId");
		String policyRef = request.getParameter("policyRef");
		String flag = request.getParameter("flag");
		String ty = request.getParameter("type");
		String fileName = PropertiesUtil.getProperty("quoPdfURLPrefix") + ty
				+ "?contractId=" + contractId + "&partner=NEWTOUCH&sign="
				+ StringUtil.getAZCLmd5(contractId + "NEWTOUCH");
		String pdfUrl = "private/NOTE/" + policyRef + "/" + contractId
				+ "/unsign/" + ty + ".pdf";
		String pdfPath = PropertiesUtil.getResourcePath() + pdfUrl;
		File file = new File(pdfPath);
		if (!file.exists()) {
			file.getParentFile().mkdirs();
			file.createNewFile();
		}
		;
		HttpsUtil.httpsPost_pdf_download(fileName, pdfPath);
		List<File> pdf2jpg = Pdf2TifUtil.pdf2jpg(new File(pdfPath),
				PropertiesUtil.getResourcePath() + "private/NOTE/pdf2jpg/"
						+ policyRef + "/" + contractId + "/");
		String type = "jpg";
		File f = pdf2jpg.get(Integer.parseInt(flag));
		int length = 0;
		ServletOutputStream op;
		try {
			op = response.getOutputStream();
		} catch (IOException e) {
			throw new IOException("io流错误");
		}
		response.setContentLength((int) f.length());
		response.setContentType("image/jpeg");
		response.setHeader("Content-Disposition", "inline; filename=" + type);
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "No-cache");
		response.setHeader("Cache-Control", "no-store");
		response.setDateHeader("Expires", 0);

		byte[] bytes = new byte[1024];
		DataInputStream in;
		try {
			in = new DataInputStream(new FileInputStream(f));
			while ((in != null) && ((length = in.read(bytes)) != -1)) {
				op.write(bytes, 0, length);
			}
			op.close();
			in.close();
			response.flushBuffer();
		} catch (FileNotFoundException e) {
			throw new Exception("文件未找到");
		} catch (IOException e) {
			throw new IOException("io流错误");
		}

	}

	@RequestMapping("/createPdf")
	@ResponseBody
	public void createPdf(@RequestParam(value = "jsonParam") String jsonParam,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JSONObject obj = JSONObject.fromObject(jsonParam);
		String policyRef = (String) obj.get("policyRef");
		String contractId = (String) obj.get("contractId");
		String html = (String) obj.get("html");
		String wenben = (String) obj.get("wenben");
		String type = obj.getString("type");
		String productName = obj.getString("productName");
		String agentName = obj.getString("agentName");
		String agentCode = obj.getString("agentCode");
		String phName = obj.getString("phName");

		File file = new File(REALPARH + "private/NOTE/" + policyRef + "/"
				+ contractId + "/unsign/" + type + ".pdf");
		if (!file.exists()) {
			file.getParentFile().mkdirs();
			file.createNewFile();
		}
		HtmlParseService.HtmlParse(NoteController.class
				.getResource("/PdfHtml/affirmNoteReply-PDF.html"), html,
				wenben, policyRef, productName, REALPARH
						+ "private/NOTE/" + policyRef + "/" + contractId
						+ "/unsign/" + type + ".pdf",agentCode,agentName,phName);
	}

	// 查询noteContent 界面Oliver数据
	@RequestMapping("/initContent")
	@ResponseBody
	public Map<String, Object> initContent(
			@RequestParam(value = "jsonParam") String jsonParam,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		CustomerContextHolder
				.setCustomerType(CustomerContextHolder.DATA_SOURCE_ALLIANZ);
		AdT2NoticeRecordsKey nr;
		try {
			nr = objectMapper.readValue(jsonParam, AdT2NoticeRecordsKey.class);
		} catch (Exception e) {
			throw new Exception("未查询到数据");
		}
		Assert.notNull(nr.getContractId(), "未提供数据");
		Map<String, Object> map = adT2NoticeRecordsService.initContent(nr);
		return map;
	}

	// 查询noteContent 界面Oliver数据
	@RequestMapping("/initMyContent")
	@ResponseBody
	public Map<String, Object> initMyContent(
			@RequestParam(value = "jsonParam") String jsonParam,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		CustomerContextHolder
				.setCustomerType(CustomerContextHolder.DATA_SOURCE_NEWTOUCH);
		Map<String, Object> map = new HashMap<String, Object>();
		Note note;
		try {
			note = objectMapper.readValue(jsonParam, Note.class);
		} catch (Exception e) {
			throw new Exception("未查询到数据");
		}
		Assert.notNull(note.getContractId(), "未提供数据");
		Note queryNote = noteService.queryNote(note);
		if (queryNote == null) {
			map.put("flag", "01");
			return map;
		}
		map.put("flag", "00");
		map.put("result", queryNote);
		return map;
	}

	// 插入 界面Oliver数据
	@RequestMapping("/insertMyContent")
	@ResponseBody
	public Map<String, Object> insertMyContent(
			@RequestParam(value = "jsonParam") String jsonParam,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		CustomerContextHolder
				.setCustomerType(CustomerContextHolder.DATA_SOURCE_NEWTOUCH);
		Map<String, Object> map = new HashMap<String, Object>();
		Note note;
		try {
			note = objectMapper.readValue(jsonParam, Note.class);
		} catch (Exception e) {
			throw new Exception("未查询到数据");
		}
		Assert.notNull(note.getContractId(), "未提供数据");
		int queryNote = noteService.addNote(note);
		map.put("result", queryNote);
		return map;
	}

	// 插入 界面Oliver数据
	@RequestMapping("/updateMyContent")
	@ResponseBody
	public Map<String, Object> updateMyContent(
			@RequestParam(value = "jsonParam") String jsonParam,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		CustomerContextHolder
				.setCustomerType(CustomerContextHolder.DATA_SOURCE_NEWTOUCH);
		Map<String, Object> map = new HashMap<String, Object>();
		Note note;
		try {
			note = objectMapper.readValue(jsonParam, Note.class);
		} catch (Exception e) {
			throw new Exception("未查询到数据");
		}
		Assert.notNull(note.getContractId(), "未提供数据");
		int queryNote = noteService.updateNote(note);
		map.put("result", queryNote);
		return map;
	}

	// 查询noteContent 界面Oliver数据
	@RequestMapping("/QCBodySignCA")
	@ResponseBody
	public void QCBodySignCA(
			@RequestParam(value = "jsonParam") String jsonParam,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		/*
		 * 准备数据 pdfMessage 图片和pdf ca中有type policyRef
		 */
		BJCApojo ca;
		try {
			ca = objectMapper.readValue(jsonParam, BJCApojo.class);
		} catch (Exception e) {
			throw new Exception("签字数据异常,请确认已完成签字拍照");
		}
		List<PdfMessage> pdfMessage = ca.getPdfMessageList();
		if (pdfMessage.size() == 0) {
			throw new Exception("签字数据异常,请确认已完成签字拍照");
		}
		String policyRef = ca.getPolicyRef();
		String contractId = ca.getInsured();
		String unsignPdfPath;
		String signedPdfPath;

		/*
		 * 准备数据 循环数据 上传至影像系统
		 */

		for (PdfMessage pdf : pdfMessage) {
			/*
			 * 上传照片
			 */
			String encode = pdf.getEncode();
			String encodePath = REALPARH + "private/NOTE/" + policyRef
					+ "/" + contractId + "/" + "unsign/" + pdf.getPdfType()
					+ ".txt";
			FileWriter fw = null;
			if (StringUtil.isNull(encode)) {
				throw new Exception("加密包不能为空");
			} else {
				fw = new FileWriter(encodePath);
				fw.write(encode);
				fw.flush();
				fw.close();
			}
			List<String> photoList = pdf.getPhotoList();
			for (int i = 0; i < photoList.size(); i++) {
				ImageUploadService
						.uploadUtil(photoList.get(i),
								REALPARH + "private/NOTE/" + policyRef
										+ "/" + contractId + "/" + "signed/"
										+ pdf.getPdfType() + "_" + i + ".jpg");
			}

			/*
			 * 将http下的pdf下载到未签名的文件夹中
			 */
			// 未签名的pdf目录路径：
			unsignPdfPath = REALPARH + "private/NOTE/" + policyRef + "/"
					+ contractId + "/" + "unsign/" + pdf.getPdfType() + ".pdf";
			// 签名后的pdf目录路径：
			signedPdfPath = REALPARH + "private/NOTE/" + policyRef + "/"
					+ contractId + "/" + "signed/" + pdf.getPdfType() + ".pdf";
			String pdfUrl = pdf.getPdfURL();
			// 先生成文件 再复制
			File file = new File(unsignPdfPath);
			if (!file.exists()) {
				file.getParentFile().mkdirs();
				file.createNewFile();
			}
			;
			HttpsUtil.httpsPost_pdf_download(pdfUrl, unsignPdfPath);
			/*
			 * 调用ca接口 生成合成pdf
			 */

			int repeat = 5;
			boolean result = false;
			while (repeat > 0) {
				result = CaPdfService.makeCaPdf(encodePath, unsignPdfPath,
						signedPdfPath, ca.getPolicyRef());
				if (result)
					break;
				repeat--;
				Thread.sleep(2000);
			}
			if (!result) {
				throw new Exception("CA异常,请待会重试");
			}

			/*
			 * 生成tif文件
			 */
			File signedPdfPathFile = new File(signedPdfPath);
			boolean tifResult = CaPdfService.pdfToTif(signedPdfPathFile,
					signedPdfPathFile.getParentFile().getAbsolutePath()
							+ File.separator, pdf.getPdfType());
			if (!tifResult) {
				throw new Exception("tif合成工具异常,请待会重试");
			}
		}
	}

	@RequestMapping("/NoteAffirmCA")
	@ResponseBody
	public void NoteAffirmCA(
			@RequestParam(value = "jsonParam") String jsonParam,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		/*
		 * 准备数据 pdfMessage 图片和pdf ca中有type policyRef
		 */
		BJCApojo ca;
		try {
			ca = objectMapper.readValue(jsonParam, BJCApojo.class);
		} catch (Exception e) {
			throw new Exception("签字数据异常,请确认已完成签字拍照");
		}
		List<PdfMessage> pdfMessage = ca.getPdfMessageList();
		if (pdfMessage.size() == 0) {
			throw new Exception("签字数据异常,请确认已完成签字拍照");
		}
		String policyRef = ca.getPolicyRef();
		String contractId = ca.getInsured();
		String unsignPdfPath;
		String signedPdfPath;
		/*
		 * 准备数据 循环数据 上传至影像系统
		 */

		for (PdfMessage pdf : pdfMessage) {
			/*
			 * 上传照片
			 */
			String encode = pdf.getEncode();
			String encodePath = REALPARH + "private/NOTE/" + policyRef
					+ "/" + contractId + "/" + "unsign/" + pdf.getPdfType()
					+ ".txt";
			FileWriter fw = null;
			if (StringUtil.isNull(encode)) {
				throw new Exception("加密包不能为空");
			} else {
				fw = new FileWriter(encodePath);
				fw.write(encode);
				fw.flush();
				fw.close();
			}
			List<String> photoList = pdf.getPhotoList();
			for (int i = 0; i < photoList.size(); i++) {
				ImageUploadService
						.uploadUtil(photoList.get(i),
								REALPARH + "private/NOTE/" + policyRef
										+ "/" + contractId + "/" + "signed/"
										+ pdf.getPdfType() + "_" + i + ".jpg");
			}

			/*
			 * 将http下的pdf下载到未签名的文件夹中
			 */
			// 未签名的pdf目录路径：
			unsignPdfPath = REALPARH + "private/NOTE/" + policyRef + "/"
					+ contractId + "/" + "unsign/" + pdf.getPdfType() + ".pdf";
			// 签名后的pdf目录路径：
			signedPdfPath = REALPARH + "private/NOTE/" + policyRef + "/"
					+ contractId + "/" + "signed/" + pdf.getPdfType() + ".pdf";

			// 先生成文件 再复制
			/*
			 * 调用ca接口 生成合成pdf
			 */

			int repeat = 5;
			boolean result = false;
			while (repeat > 0) {
				result = CaPdfService.makeCaPdf(encodePath, unsignPdfPath,
						signedPdfPath, ca.getPolicyRef());
				if (result)
					break;
				repeat--;
				Thread.sleep(2000);
			}
			if (!result) {
				throw new Exception("CA异常,请待会重试");
			}

			/*
			 * 生成tif文件
			 */
			File signedPdfPathFile = new File(signedPdfPath);
			boolean tifResult = CaPdfService.pdfToTif(signedPdfPathFile,
					signedPdfPathFile.getParentFile().getAbsolutePath()
							+ File.separator, pdf.getPdfType());
			if (!tifResult) {
				throw new Exception("tif合成工具异常,请待会重试");
			}
		}
	}

	
// 插入 界面Oliver数据
	@RequestMapping("/uploadAll")
	@ResponseBody
	public void uploadAll(@RequestParam(value = "jsonParam") String jsonParam,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JSONObject obj = JSONObject.fromObject(jsonParam);
		List<String> typeList = (List<String>) obj.get("typeList");
		String policyRef = (String) obj.get("policyRef");
		String contractId = (String) obj.get("contractId");
		String preprintedNo = (String) obj.get("preprintedNo");
		Assert.notNull(typeList, "未获得所拍照片");
		Assert.hasLength(policyRef, "未获得保单号");
		Assert.notEmpty(typeList, "文件类型不能为空");
		String ip = ImageUploadService.getIP(request);
		String flagFileString_photo_Directory = REALPARH + "private/NOTE/"
				+ policyRef + "/" + contractId + "/" + "signed/";
		Map<String, List<File>> filesMap = ImageUploadService
				.getPhotoMap(policyRef, contractId, typeList,
						flagFileString_photo_Directory);
		ImageUploadService.shadowXMLandFolderCreate(policyRef, "NOTE", ip,
				filesMap, new Date(), contractId,preprintedNo);
	}
	
	// 插入 界面Oliver数据
	@RequestMapping("/getProductName")
	@ResponseBody
	public Map<String, Object> getProductName(
			@RequestParam(value = "jsonParam") String jsonParam,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		CustomerContextHolder
				.setCustomerType(CustomerContextHolder.DATA_SOURCE_ALLIANZ);
		Note qc = objectMapper.readValue(jsonParam, Note.class);
		return noteService.queryProduct(qc.getContractId());
	}
	@RequestMapping("/checkContractId")
	@ResponseBody
	public Map<String, Object> checkContractId(
			@RequestParam(value = "jsonParam") String jsonParam,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		CustomerContextHolder
				.setCustomerType(CustomerContextHolder.DATA_SOURCE_NEWTOUCH);
		JSONObject obj = JSONObject.fromObject(jsonParam);
		List<Integer> contractIdList = (List<Integer>) obj.get("contractIdList");
		Assert.notEmpty(contractIdList,"contractId不能为空");
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("contractId", noteService.queryContractId(contractIdList));
		return map;
	}
}
